package com.jiangyg.mall.ware.listener;

import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.order.dto.OrderReleaseDTO;
import com.jiangyg.mall.ware.dto.StockReleaseDTO;
import com.jiangyg.mall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 类描述：库存释放监听
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-12-19
 */
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "stock.release.queue", autoDelete = "false"),
        exchange = @Exchange(value = "stock-event-exchange", type = ExchangeTypes.TOPIC)
))
public class StockReleaseQueueListener {

    private final WareSkuService wareSkuService;

    @Autowired
    public StockReleaseQueueListener(WareSkuService wareSkuService) {
        this.wareSkuService = wareSkuService;
    }

    /**
     * 功能描述：通过订单发起的库存解锁
     *
     * @param dto     订单释放对象
     * @param channel 通道
     * @param message 消息
     * @throws IOException 异常
     */
    @RabbitHandler
    public void listener(OrderReleaseDTO dto, Channel channel, Message message) throws IOException {
        try {
            Logger.info(log, () -> String.format("[订单发起库存解锁监听]-监听到订单[%d]已关闭，开始库存解锁处理……", dto.getId()));
            wareSkuService.unlockStock(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            Logger.info(log, () -> String.format("[订单发起库存解锁监听]-订单[%d]库存解锁处理出错", dto.getId()), ex);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 功能描述：库存锁定超时触发的库存解锁
     *
     * @param dto     库存释放对象
     * @param channel 通道
     * @param message 消息
     * @throws IOException 异常
     */
    @RabbitHandler
    public void listener(StockReleaseDTO dto, Channel channel, Message message) throws IOException {
        try {
            Logger.info(log, () -> String.format("[库存超时触发解锁监听]-监听到工作单详情[%d]已超时，开始库存解锁处理……", dto.getOrderTaskDetailId()));
            wareSkuService.unlockStock(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            Logger.info(log, () -> String.format("[库存超时触发解锁监听]-工作单详情[%d]已超时处理出错", dto.getOrderTaskDetailId()), ex);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
